/**
 *
 */
package com.creditease.mobile.news.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.creditease.mobile.BaseActivity;
import com.creditease.mobile.R;
import com.creditease.mobile.comp.PullToRefreshListView;
import com.creditease.mobile.news.adapter.NewsAdapter;
import com.creditease.mobile.news.db.DBUtils;
import com.creditease.mobile.news.db.NewsSQLiteOpenHelper;
import com.creditease.mobile.news.model.NewsModel;
import com.creditease.mobile.news.util.NewsDownloadTask;
import com.creditease.mobile.news.util.NewsListDownloadTask;
import com.creditease.mobile.rss.RssConst;
import com.creditease.mobile.rss.ui.SettingActivity;
import com.creditease.mobile.util.NetUtil;
import com.creditease.mobile.util.PrefHelper;
import com.creditease.mobile.util.TimeUtil;
import com.creditease.mobile.vo.TopVo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 首页内容 title description
 *
 * @author Administrator
 * @version 1.1.0
 * @since 2012-5-12
 */
public class NewsHomeActivity extends BaseActivity {

    private TextView titleText;
    private PullToRefreshListView listView;
    private TableRow tableRow;
    private int currentIndex = 0;
    private NewsSQLiteOpenHelper dbHelper;
    private List<TextView> titlesTextViews;
    private Handler handler;
    private ImageView reflushView;
    private static final int MSG_SUCCESS = 0;//
    private static final int MSG_FAILURE = 1;//
    private static final int MSG_REFLUSH = 2;//
    private static final int ADD_FAILURE = 3;//
    private List<NewsModel> newsList;
    private NewsAdapter adapter;
    private ProgressBar progressBar;
    private String TAG = NewsHomeActivity.class.getName();
    private ProgressDialog loadingDialog;

    private Button loadMoreButton;
    private View loadMoreView;
    private int newsStartId = 0;
    private int newsPage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_home);
        // 标题
        titleText = (TextView) findViewById(R.id.titleText);
        titleText.setText(R.string.app_name);

        //        tableRow = (TableRow) findViewById(R.id.newsTitles);
        loadMoreView = getLayoutInflater().inflate(R.layout.list_loadingmore, null);
        loadMoreButton = (Button) loadMoreView.findViewById(R.id.moreRssBtn);

        dbHelper = new NewsSQLiteOpenHelper(getApplicationContext());
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                switch (msg.what) {
                    case MSG_SUCCESS:// 将进度条可见
                        reflush();
                        if (loadingDialog != null) {
                            loadingDialog.cancel();
                            loadingDialog = null;
                        }
                        if (loadMore) {
                            loadMoreButton.setText(R.string.moreRss); // 恢复按钮文字
                            progressBar.setVisibility(View.INVISIBLE);
                            reflushView.setVisibility(View.VISIBLE);
                            loadMore = false;
                        }
                        if (onRefresh) {
                            progressBar.setVisibility(View.INVISIBLE);
                            reflushView.setVisibility(View.VISIBLE);
                            String currentCid = getNameList().get(currentIndex).cid;
                            Long time = new Date().getTime();
                            Long updateTime = PrefHelper.getLong(getApplication(), currentCid, time);
                            String s = TimeUtil.getDescriptionTimeFromTimestamp(updateTime);
                            Log.d(TAG, "time=" + time);
                            Log.d(TAG, "updateTime=" + updateTime);
                            Log.d(TAG, "" + s);
                            // 刷新完成调用该方法复位
                            listView.onRefreshComplete(s + RssConst.UPDATE_SUFFIX);
                            onRefresh = false;
                        }
                        Log.d(TAG, "MSG_SUCCESS");
                        progressBar.setVisibility(View.INVISIBLE);
                        reflushView.setVisibility(View.VISIBLE);
                        Toast.makeText(getApplicationContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                        refreshAble = true;
                        break;
                    case MSG_FAILURE:
                        Log.d(TAG, "MSG_FAILURE");
                        progressBar.setVisibility(View.INVISIBLE);
                        reflushView.setVisibility(View.VISIBLE);
                        Toast.makeText(getApplicationContext(),
                                R.string.neterr, Toast.LENGTH_SHORT).show();
                        if (loadingDialog != null) {
                            loadingDialog.cancel();
                            loadingDialog = null;
                        }
                        if (loadMore) {
                            loadMoreButton.setText(R.string.moreRss); // 恢复按钮文字
                            loadMore = false;
                        }
                        // 刷新完成调用该方法复位
                        if (onRefresh) {
                            listView.onRefreshComplete();
                            onRefresh = false;
                        }
                        refreshAble = true;
                        break;
                    case MSG_REFLUSH:
                        Log.d(TAG, "MSG_REFLUSH");
                        reflush();
                        if (loadingDialog != null) {
                            loadingDialog.cancel();
                            loadingDialog = null;
                        }
                        if (loadMore) {
                            loadMoreButton.setText(R.string.moreRss); // 恢复按钮文字
                            progressBar.setVisibility(View.INVISIBLE);
                            reflushView.setVisibility(View.VISIBLE);
                            loadMore = false;
                        }
                        if (onRefresh) {
                            progressBar.setVisibility(View.INVISIBLE);
                            reflushView.setVisibility(View.VISIBLE);
                            String currentCid = getNameList().get(currentIndex).cid;
                            Long time = new Date().getTime();
                            Long updateTime = PrefHelper.getLong(getApplication(), currentCid, time);
                            String s = TimeUtil.getDescriptionTimeFromTimestamp(updateTime);
                            Log.d(TAG, "time=" + time);
                            Log.d(TAG, "updateTime=" + updateTime);
                            Log.d(TAG, "" + s);
                            // 刷新完成调用该方法复位
                            listView.onRefreshComplete(s + RssConst.UPDATE_SUFFIX);
                            onRefresh = false;
                        }
                        // Toast.makeText(getApplicationContext(), "加载成功", Toast.LENGTH_SHORT).show();
                        refreshAble = true;
                        break;
                }
            }
        };
        // T1295501906343
        String tid = "T1295501906343";
        newsList = getData(tid, 0);

        adapter = new NewsAdapter(getApplicationContext(), newsList);
        listView = (PullToRefreshListView) findViewById(R.id.news_List);

        listView.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (refreshAble) {
                    //将开始设置为：0
                    newsStartId = 0;
                    newsPage = 0;
                    //设置刷新标识
                    onRefresh = true;
                    progressBar.setVisibility(View.VISIBLE);
                    reflushView.setVisibility(View.INVISIBLE);
                    // 在这执行后台工作
                    List<TopVo> nameList = new ArrayList<TopVo>();
                    TopVo vo = getNameList().get(currentIndex);
                    nameList.add(new TopVo(vo.cid, vo.cname));
                    Log.d(TAG, "刷新内容：" + vo.cname);
                    rssCount = nameList.size();
                    indexCount = 0;
                    NewsListDownloadTask taskList = new NewsListDownloadTask();
                    taskList.execute(dbHelper, nameList, NewsHomeActivity.this, newsStartId, 20);
                    refreshAble = false;
                }
            }
        });

        // 需要放在 setAdapter之前，否则不显示
        if (newsList.isEmpty()) {

            listView.setEmptyView(findViewById(R.id.newsEmptyMsg));
        } else {
            listView.addFooterView(loadMoreView);
        }

        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                NewsModel item = (NewsModel) parent.getItemAtPosition(position);
                final Intent intent = new Intent();
                intent.setClass(NewsHomeActivity.this, NewsReaderActivity.class);
                intent.putExtra("docid", item.docid);
                intent.putExtra("cid", item.cid);
                intent.putExtra("newsTitle", item.title);
                startActivity(intent);
            }
        });
        final List<TopVo> titles = getNameList();

        Long time = new Date().getTime();
        Long updateTime = PrefHelper.getLong(getApplication(), tid, time);
        String s = TimeUtil.getDescriptionTimeFromTimestamp(updateTime);

        listView.setLastUpdated(s + RssConst.UPDATE_SUFFIX);

        // 包含TextView的LinearLayout
        LinearLayout menuLinerLayout = (LinearLayout) findViewById(R.id.newsTitles);
        menuLinerLayout.setOrientation(LinearLayout.HORIZONTAL);
        // 参数设置
        LinearLayout.LayoutParams menuLinerLayoutParames = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1);
        menuLinerLayoutParames.gravity = Gravity.CENTER_HORIZONTAL;
        titlesTextViews = new ArrayList<TextView>();
        for (int col = 0; col < 6; col++) {
            // tv用于显示
            TopVo vo = titles.get(col);
            TextView tv = new TextView(this);
            tv.setText(vo.cname);
            tv.setTextColor(R.color.black);
            tv.setGravity(Gravity.CENTER);
            tv.setLayoutParams(new LinearLayout.LayoutParams(30, 38));

            tv.setTextSize(16);
            tv.setPadding(15, 10, 15, 10);

            final int index = col;
            tv.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (index == currentIndex) {
                        return;
                    }

                    //第一个参数fromXDelta为动画起始时 X坐标上的移动位置
                    //第二个参数toXDelta为动画结束时 X坐标上的移动位置
                    //第三个参数fromYDelta为动画起始时Y坐标上的移动位置
                    //第四个参数toYDelta为动画结束时Y坐标上的移动位置
                    //将开始设置为：0
                    newsStartId = 0;
                    newsPage = 0;
                    setTitleIndex(index);
                    Log.d(TAG, "start=" + startX + ",to=" + v.getLeft());
                    int to = v.getLeft() - v.getWidth() * (index + 1) - startX;
                    Log.d(TAG, "to=" + to);
                    TranslateAnimation animation2 = new TranslateAnimation(startX - v.getLeft(), 0, 0, 0);
                    animation2.setDuration(200);
                    v.setAnimation(animation2);

                    Animation animation = AnimationUtils.loadAnimation(getApplication(), android.R.anim.fade_in);
                    animation.setDuration(500);
                    listView.setAnimation(animation);
                    String cid = titles.get(index).cid;
                    newsList = getData(cid, 0);
                    adapter = new NewsAdapter(getApplicationContext(), newsList);
                    listView.setAdapter(adapter);
                    startX = v.getLeft();
                    Long time = new Date().getTime();
                    Long updateTime = PrefHelper.getLong(getApplication(), cid, time);

                    String s = TimeUtil.getDescriptionTimeFromTimestamp(updateTime);
                    Log.d(TAG, "time=" + time);
                    Log.d(TAG, "updateTime=" + updateTime);
                    Log.d(TAG, "" + s);
                    listView.setLastUpdated(s + RssConst.UPDATE_SUFFIX);
                }
            });
            menuLinerLayout.addView(tv, menuLinerLayoutParames);
            titlesTextViews.add(tv);
        }
        setTitleIndex(0);
        reflushView = (ImageView) findViewById(R.id.reflushIcon);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        // 给刷新按钮 添加刷新事件
        reflushView.setOnClickListener(new ReflushClickListener());
        loadMoreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadMoreButton.setText(R.string.loadingMsg); // 设置按钮文字
                loadMore = true;
                progressBar.setVisibility(View.VISIBLE);
                reflushView.setVisibility(View.INVISIBLE);
                newsPage++;
                TopVo vo = getNameList().get(currentIndex);
                newsStartId = (newsPage * 20);
                Log.d(TAG, "刷新内容：" + vo.cname + ",开始于：" + newsStartId + 1);
                List list = getData(vo.cid, newsStartId);
                if (!list.isEmpty()) {
                    handler.obtainMessage(MSG_REFLUSH).sendToTarget();
                }
                ;
            }
        });
    }

    private boolean onRefresh = false;
    private boolean loadMore = false;
    private int startX = 0;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(0, 1, 1, R.string.menu_reflush).setIcon(R.drawable.menu_download);
        menu.add(0, 2, 2, R.string.menu_setting).setIcon(R.drawable.menu_setting);
        //        menu.add(0, 7, 7, R.string.menu_about);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            //下载
            downloadNews();
        } else if (item.getItemId() == 2) {
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), SettingActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    private void downloadNews() {
        // 如果网络不可用
        if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
            handler.obtainMessage(MSG_FAILURE).sendToTarget();
            return;
        }
        // 将进度条可见
        progressBar.setVisibility(View.VISIBLE);
        reflushView.setVisibility(View.INVISIBLE);
        List<TopVo> list = getNameList();
        rssCount = list.size();
        indexCount = 0;
        NewsDownloadTask task = new NewsDownloadTask();
        task.execute(dbHelper, list, this);
    }

    public void reflush() {
        String currentCid = getNameList().get(currentIndex).cid;
        Log.d(TAG, "currentCid=" + currentCid);
        List<NewsModel> list = getData(currentCid, newsStartId);
        if (newsStartId == 0) {
            newsList.clear();
            adapter.updateView();
        } else {

        }

        newsList.addAll(list);
        adapter.notifyDataSetChanged();
    }

    public List<TopVo> getNameList() {
        List<TopVo> vos = new ArrayList<TopVo>();
        vos.add(new TopVo("T1295501906343", "头条"));
        vos.add(new TopVo("T1295505916992", "体育"));
        vos.add(new TopVo("T1295506658957", "娱乐"));
        vos.add(new TopVo("T1295505705196", "财经"));
        vos.add(new TopVo("T1295507084100", "科技"));
        vos.add(new TopVo("T1295505330581", "国内"));
        return vos;
    }

    private void setTitleIndex(int index) {

        TextView oldSelected = titlesTextViews.get(currentIndex);
        oldSelected.setBackgroundResource(R.color.transparent);
        oldSelected.setTextColor(R.color.black);

        TextView n = titlesTextViews.get(index);
        n.setBackgroundResource(R.drawable.shape);
        n.setTextColor(Color.WHITE);
        currentIndex = index;
    }

    private List<NewsModel> getData(String tid, int newsStartId) {
        Log.d(TAG, "从数据库获取数据，开始于：" + newsStartId);
        List<NewsModel> list = DBUtils.getDataFromNewsListTable(dbHelper, tid, newsStartId, 20);
        Log.d(TAG, "size=" + list.size());
        if (list.isEmpty() && refreshAble) {
            // 如果网络不可用
            if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
                handler.obtainMessage(MSG_FAILURE).sendToTarget();
                return new ArrayList<NewsModel>();
            }
            Log.d("Remote", "从网络获取数据开始...");
            //            newsList=newsServices.getRemoteData(tid,dbHelper);
            //            Log.d("Remote", "从网络获取数据结束.");
            if (newsStartId == 0) {
                loadingDialog = showDailog("数据加载中，请稍候...");
            }

            List<TopVo> nameList = new ArrayList<TopVo>();
            nameList.add(new TopVo(tid, "tid"));
            rssCount = nameList.size();
            indexCount = 0;
            NewsListDownloadTask taskList = new NewsListDownloadTask();
            taskList.execute(dbHelper, nameList, this, newsStartId, 20);
            refreshAble = false;
        }
        return list;
    }

    // 刷新所有订阅 新闻
    private void refreshAllNews() {
        // 如果网络不可用
        if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
            handler.obtainMessage(MSG_FAILURE).sendToTarget();
            return;
        }
        if (refreshAble) {
            onRefresh = true;
            // 将进度条可见
            progressBar.setVisibility(View.VISIBLE);
            reflushView.setVisibility(View.INVISIBLE);
            List<TopVo> list = getNameList();
            rssCount = list.size();
            indexCount = 0;
            NewsListDownloadTask taskList = new NewsListDownloadTask();
            taskList.execute(dbHelper, list, this, 0, 20);
            refreshAble = false;
        }
    }

    private boolean refreshAble = true;

    private final class ReflushClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            refreshAllNews();
        }
    }

    private ConcurrentHashMap<String, String> stateMap = new ConcurrentHashMap<String, String>();
    private int rssCount = 0;
    private int indexCount = 0;

    @Override
    public void reflushCallBack(boolean cancel, String... params) {
        String state = params[0];
        String cid = params[1];
        stateMap.put(state, state);
        indexCount++;
        String currentCid = getNameList().get(currentIndex).cid;
        Log.d(TAG, "完成：" + indexCount + ",共：" + rssCount);
        if ("false".equals(state)) {
            handler.obtainMessage(MSG_FAILURE).sendToTarget();
            return;
        }

        Long time = new Date().getTime();
        PrefHelper.putLong(getApplication(), cid, time);

        /*if (currentCid.equals(cid)) {
            handler.obtainMessage(MSG_REFLUSH).sendToTarget();
        } else */
        if (indexCount == rssCount || cancel) {
            if (stateMap.size() == 1) {
                handler.obtainMessage(MSG_SUCCESS).sendToTarget();
            } else {
                handler.obtainMessage(MSG_FAILURE).sendToTarget();
            }
        }
    }
}
